import {deepCopy} from "@/utils";
import {WidgetFactory} from "@/modules/IDE/widgetFactory";

export class PageHandler {
  constructor(type) {
    this.type = type; // page/subPage/component
    this.pages = [];
    this.activePage = undefined;
    this.activePageForPicker = undefined;
    this.baseCfg = {};
  }

  initPages(widgets = [], baseCfg = {}, createDefault = true) {
    this.baseCfg = baseCfg;
    this.pages = WidgetFactory.assembleWidgetFromArray(widgets);
    if (this.pages.length) {
      this.activePage = this.pages[0];
      this.activePageForPicker = this.activePage;
    } else {
      createDefault && this.createRootPage();
    }
  }

  // 创建根页面
  createRootPage(config = {}) {
    const {isAppendage = false} = config;
    const pages = this.pages;
    let rootPage;
    switch (this.type) {
      case 'page':
        rootPage = WidgetFactory.createPageRoot(this.baseCfg);
        break;
      case 'subPage':
        rootPage = WidgetFactory.createSubPageRoot(this.baseCfg);
        break;
      case 'component':
        if (!isAppendage) {
          rootPage = WidgetFactory.createComponentRoot(this.baseCfg);
        } else {
          rootPage = WidgetFactory.createComponentAppendage({...this.baseCfg, ...config});
        }
        break;
      default:
        break;
    }
    pages.push(rootPage);
    this.pages = pages;
    this.refreshPageWidgetSortNo();
    this.activePage = this.pages[this.pages.length - 1];
    this.activePageForPicker = this.activePage;
    return rootPage;
  }

  // 拷贝页面
  clonePage(page) {
    const index = this.pages.findIndex(p => p.id === page.id);
    const name = `${page.name}-副本`;
    const clonePage = WidgetFactory.copyWidget({...page, name}, true);
    this.pages.splice(index + 1, 0, clonePage);
    this.refreshPageWidgetSortNo();
    this.activePage = clonePage;
    return clonePage;
  }

  // 删除页面
  deletePage(srcPage = {}) {
    const deletedWidgets = WidgetFactory.deleteWidget(srcPage);
    this.refreshPageWidgetSortNo();
    // 删除 page 后默认选中第一个 page
    this.activePage = this.pages[0];
    return deletedWidgets;
  }

  // 设置某页面为首页
  setHomepage(pageId = '') {
    // 把某个页面设为首页后，其他页面的默认显示状态改为隐藏
    this.pages.forEach(page => {
      page.visible = page.id === pageId;
      const visiblePort = page.ports.values.find(val => val.key === 'visible') || {};
      visiblePort.value = page.visible;
    });
  }

  updateActivePage(widget = {}, isForPicker = false) {
    const {contain, index} = this.judgePageContainWidget(widget);
    if (!contain) return;
    if (!isForPicker) {
      this.activePage = this.pages[index];
    } else {
      this.activePageForPicker = this.pages[index];
    }
  }

  // 判断页面是否包含某个组件
  judgePageContainWidget(srcWidget = {}) {
    const fullPath = WidgetFactory.getWidgetFullPath(srcWidget.id);
    let contain = false;
    let pageBelongIdx = -1;
    for (let i = 0; i < this.pages.length; i++) {
      const page = this.pages[i];
      if (fullPath.includes(page.id)) {
        contain = true;
        pageBelongIdx = i;
        break;
      }
    }
    return {
      contain: contain,
      index: pageBelongIdx
    }
  }

  getWidgetBelongPage(srcWidget = {}) {

  }

  // 刷新页面组件的排序号
  refreshPageWidgetSortNo() {
    let deletedNum = 0; // 记录被删除的页面数量
    this.pages.forEach((page, idx) => {
      if (page.isDeleted) {
        deletedNum++;
        return;
      }
      page.sortNo = idx + 1 - deletedNum;
      WidgetFactory.refreshWidgetSortNo(page);
    });
  }

  // 将页面的树形结构组件扁平化，用于后台接口调用
  static getPageFlattenWidgets(pages = [], ignoreSubPage = false) {
    if (!pages.length) return [];
    const widgetValidKeys = [
      'hash', '_id', 'id', 'editId', 'parentId',
      'sourceId', 'roomId', 'componentId',
      'subPageId', 'relateSubPage', 'relateSubPageId',
      'type', 'category', 'name','rect', 'UI', 'ports',
      'isRoot', 'display', 'visible', 'isAppendage','appendageId','appendDialogId',
      'draggable', 'droppable', 'resizable', 'selectable',
      'isLocked', 'isFreeze', 'isChildrenFreeze', 'isEditing',
      'isDeleted', 'sortNo', 'editId', 'editableByControl'
    ];
    const widgets = [];
    pages.forEach(page => {
      WidgetFactory.getWidgetFlattenChildren(page).forEach(w => {
        const widget = deepCopy(w);
        const {_id, id, subPageId, isDeleted} = widget;
        // 过滤掉新创建又被删除的组件
        if (!_id && isDeleted) return;
        // 主页数据保存需要过滤掉关联子页的子组件内容
        if (ignoreSubPage && subPageId) return;
        // const {origin = '', current = ''} = WidgetFactory.widgetHashMap[id];
        // if (origin !== current) {
          const destWidget = {};
          widgetValidKeys.forEach(key => destWidget[key] = widget[key]);
          widgets.push(destWidget);
        // }
      });
    });
    return widgets;
  }
}
